//
//  centerViewController.m
//  LCSJieMianApp
//
//  Created by 千锋 on 15/12/18.
//  Copyright (c) 2015年 1000phone. All rights reserved.
//

#import "centerViewController.h"

#import "touchProppagetedScrollView.h"
#import "categoryModel.h"
#import "LCSNetworkingManager.h"
#import "LCSTools.h"
#import "firstTableViewModel.h"
#import "ScrollViewCell.h"
#import "NewsViewCell.h"
#import "leftViewController.h"
#import "rightViewController.h"
#import <RESideMenu.h>
#import "tableViewController.h"
#define CATEGROY_HEIGHT 36
#define CATEGROY_BUTTON_WIDTH 60

#define MIN_BUTTON_FONT 13.f
#define MAX_BUTTON_FONT 18.f
#define TABLEVIEW_TAG 100
#define RGBA(R/*红*/, G/*绿*/, B/*蓝*/, A/*透明*/) \
[UIColor colorWithRed:R/255.f green:G/255.f blue:B/255.f alpha:A]
@interface centerViewController ()<UIScrollViewDelegate>
{
    UIView *_categoryView;
    UIScrollView *_scrolView;

    touchProppagetedScrollView *_categoryScrol;

    float _startPointX;
    NSMutableArray *_categoryDataArray;
//    UITableView *_tableView;
    
    NSInteger _currentPage;
    BOOL _isRequest;
    
    NSMutableArray *_dataArray;

}

@property (strong, nonatomic)LCSNetworkingManager *manager;
@end

@implementation centerViewController

- (LCSNetworkingManager *)manager
{
    if (!_manager) {
        _manager = [LCSNetworkingManager manager];
    }
    return _manager;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self requestcategoryData];
    
    [self createUI];
    
}

- (void)createUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    UINavigationBar *naviBar = self.navigationController.navigationBar;
    
    [naviBar setBackgroundImage:[UIImage imageNamed:@"navigationbar"] forBarMetrics:UIBarMetricsDefault];
    UINavigationItem *naviItem = self.navigationItem;
    UIImageView *titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top_logo"]];
    naviItem.titleView = titleView;
   
    UIImage *leftImage = [[UIImage imageNamed:@"menu"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftClicked:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIImage *rightImage = [[UIImage imageNamed:@"menu_head"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:rightImage style:UIBarButtonItemStylePlain target:self action:@selector(rightClicked:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    CGSize size = self.view.frame.size;
    _categoryView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, size.width, CATEGROY_HEIGHT)];
    UIImageView *categoryPlace = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"placeholder_special_bannel"]];
    categoryPlace.frame = CGRectMake(0.f, 0.f, _categoryView.frame.size.width, _categoryView.frame.size.height);
    [_categoryView addSubview:categoryPlace];

    
    [self.view addSubview:_categoryView];
    
    _scrolView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.f, _categoryView.bounds.size.height, size.width, size.height - _categoryView.bounds.size.height)];
    _scrolView.backgroundColor = [UIColor whiteColor];
    _scrolView.pagingEnabled = YES;
    _scrolView.showsVerticalScrollIndicator = NO;
    _scrolView.showsHorizontalScrollIndicator = NO;
    _scrolView.delegate = self;
    [self.view insertSubview:_scrolView belowSubview:_categoryView];
    
 
}

#pragma mark-请求分类数据
- (void)requestcategoryData
{
    NSString *requestURL = @"http://appapi.jiemian.com/cate/all.json";
    [self.manager GET:requestURL success:^(NSURLResponse *response, NSData *data) {
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *resultArray = [[NSMutableArray alloc]init];
        resultArray = [responseDict objectForKey:@"result"];
        _categoryDataArray = [[NSMutableArray alloc] init];
        categoryModel *category = [[categoryModel alloc] init];
        [category setValuesForKeysWithDictionary:[resultArray lastObject]];
        [_categoryDataArray addObject:category];
        [resultArray removeLastObject];
        for (NSDictionary *dict in resultArray) {
            categoryModel *category = [[categoryModel alloc] init];
            [category setValuesForKeysWithDictionary:dict];
            [_categoryDataArray addObject:category];
            
            
        }
        

        dispatch_async(dispatch_get_main_queue(), ^{
            [self addCategoryButton];
        });
        
    } ];
    
}


// 添加分类button
- (void)addCategoryButton
{
    float buttonWidth = 30.f;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(_categoryView.frame.size.width - buttonWidth, 0, buttonWidth, CATEGROY_HEIGHT);
    button.backgroundColor = [UIColor colorWithRed:235 green:235 blue:235 alpha:0];
    [button setBackgroundImage:[UIImage imageNamed:@"channel_slide_icon"] forState:UIControlStateNormal];
    [_categoryView addSubview:button];
    [button addTarget:self action:@selector(showMoreCategory:) forControlEvents:UIControlEventTouchUpInside];
    
    _categoryScrol = [[touchProppagetedScrollView alloc] initWithFrame:CGRectMake(0.f, 0.f, CGRectGetMinX(button.frame), CATEGROY_HEIGHT)];
        _categoryScrol.showsVerticalScrollIndicator = NO;
    
    for (int index = 0; index < _categoryDataArray.count; index++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(CATEGROY_BUTTON_WIDTH *index, 0.f, CATEGROY_BUTTON_WIDTH, CATEGROY_HEIGHT);
        categoryModel *model = _categoryDataArray[index];
        [button setTitle:model.name forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.tag = index + 1;
        if (index == 0)
        {
            [self changeColorForButton:button red:1];
            button.titleLabel.font = [UIFont systemFontOfSize:MAX_BUTTON_FONT];
        }else
        {
            [self changeColorForButton:button red:0];
            button.titleLabel.font = [UIFont systemFontOfSize:MIN_BUTTON_FONT];
        }
        [button addTarget:self action:@selector(actionClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_categoryScrol addSubview:button];
    }
    
    _categoryScrol.contentSize = CGSizeMake(CATEGROY_BUTTON_WIDTH *_categoryDataArray.count, CATEGROY_HEIGHT);
    [_categoryView addSubview:_categoryScrol];
    
    [self createScrolView:_scrolView Count:_categoryDataArray.count Frame:CGRectZero];
    
}

// 创建滚动视图
- (void)createScrolView:(UIScrollView *)scrolView Count:(NSInteger )count Frame:(CGRect)frame
{
    
    for (int index = 0; index < count; index++) {
        tableViewController *tableControl = [[tableViewController alloc] init];
        [self addChildViewController:tableControl];
        [scrolView addSubview:tableControl.view];
        tableControl.view.frame = CGRectMake(scrolView.frame.size.width * index, 0, scrolView.frame.size.width, scrolView.frame.size.height);
        tableControl.number = TABLEVIEW_TAG + index;
        categoryModel *model = [[categoryModel alloc] init];
                    model = _categoryDataArray[index];
        tableControl.url = model.url;
    }
    
    scrolView.contentSize = CGSizeMake(count * scrolView.frame.size.width, scrolView.frame.size.height);
}


#pragma mark - 改变选中BUTTON的颜色和大小

- (void)changeColorForButton:(UIButton *)button red:(float)percent
{
    float value = [LCSTools lerp:percent min:0 max:212];
    [button setTitleColor:RGBA(value, 25, 38, 1) forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-分类按钮点击事件

- (void)actionClicked:(UIButton *)button
{
    [_scrolView scrollRectToVisible:CGRectMake(_scrolView.frame.size.width *(button.tag - 1), _scrolView.frame.origin.y, _scrolView.frame.size.width, _scrolView.frame.size.height) animated:YES];
    
    float cateScrolOffset = _scrolView.frame.size.width *(button.tag - 1) * (CATEGROY_BUTTON_WIDTH / self.view.frame.size.width) - CATEGROY_BUTTON_WIDTH;
    [_categoryScrol scrollRectToVisible:CGRectMake(cateScrolOffset, 0, _categoryScrol.frame.size.width, _categoryScrol.frame.size.height) animated:YES];
}

#pragma mark- categoryScrolViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _startPointX = scrollView.contentOffset.x;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self changeView:scrollView.contentOffset.x];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float catescrolOffset = scrollView.contentOffset.x * (CATEGROY_BUTTON_WIDTH / self.view.frame.size.width) - CATEGROY_BUTTON_WIDTH;
    [_categoryScrol scrollRectToVisible:CGRectMake(catescrolOffset, 0, _categoryScrol.frame.size.width, _categoryScrol.frame.size.height) animated:YES];
}
// 分类滚动视图假动画
- (void)changeView:(float)x
{
    float ViewOffset = x *(CATEGROY_BUTTON_WIDTH / self.view.frame.size.width);
    float startX = ViewOffset;
    int SET = x / _scrolView.frame.size.width + 1;
    if (SET <= 0) {
        return;
    }
    
    UIButton *button = (UIButton *)[_categoryScrol viewWithTag:SET];
    float percent = (startX - CATEGROY_BUTTON_WIDTH) *(SET - 1)/CATEGROY_BUTTON_WIDTH;
    float value = [LCSTools lerp:(1 - percent) min:MIN_BUTTON_FONT max:MAX_BUTTON_FONT];
    button.titleLabel.font = [UIFont systemFontOfSize:value];
    [self changeColorForButton:button red:(1 - percent)];
    
    if ((int)ViewOffset %CATEGROY_BUTTON_WIDTH == 0) {
        return;
    }
    UIButton *button2 = (UIButton *)[_categoryScrol viewWithTag:SET + 1];
    float value2 = [LCSTools lerp:percent min:MIN_BUTTON_FONT max:MAX_BUTTON_FONT];
    button2.titleLabel.font = [UIFont systemFontOfSize:value2];
    [self changeColorForButton:button2 red:percent];
}

#pragma mark - rightBUttonClicked
- (void)rightClicked:(UIBarButtonItem *)sender
{
    [self.sideMenuViewController presentRightMenuViewController];
        
}

- (void)leftClicked:(UIBarButtonItem *)sender
{
    [self.sideMenuViewController presentLeftMenuViewController];
    }



- (void)showMoreCategory:(UIButton *)sender
{
    
}
@end
